import os
from google.appengine.ext.webapp import template
from puremvc.interfaces import IMediator
from puremvc.patterns.mediator import Mediator
import app_facade
import model


class HomeMediator(Mediator, IMediator):
    NAME = "HomeMediator"

    def __init__(self, view_component):
        super(HomeMediator, self).__init__(HomeMediator.NAME, view_component)
        self.mp_proxy = self.facade.retrieve_proxy(model.MpProxy.NAME)

    def listNotificationInterests(self):
        return [app_facade.AppFacade.HOME_GOT,
                app_facade.AppFacade.MPS_GOT]

    def handleNotification(self, note):
        note_name = note.getName()

        if note_name == app_facade.AppFacade.MPS_GOT or note_name == app_facade.AppFacade.HOME_GOT:
            tfile = os.path.join(os.path.dirname(__file__), 'templates/home.html')
            tvalues = {'mps': self.mp_proxy.get_all_mps()}
            self.viewComponent.response.out.write(template.render(tfile, tvalues))


class NewMpMediator(Mediator, IMediator):
    NAME = "NewMpMediator"

    def __init__(self, view_component):
        super(NewMpMediator, self).__init__(NewMpMediator.NAME, view_component)
        self.mp_proxy = self.facade.retrieve_proxy(model.MpProxy.NAME)

    def listNotificationInterests(self):
        return [app_facade.AppFacade.MP_ADDED,
                app_facade.AppFacade.VIEW_MP_NEW]

    def handleNotification(self, note):
        note_name = note.getName()

        if note_name == app_facade.AppFacade.MP_ADDED:
            self.viewComponent.redirect("/")
        elif note_name == app_facade.AppFacade.VIEW_MP_NEW:
            tfile = os.path.join(os.path.dirname(__file__), 'templates/newmp.html')
            tvalues = {'states': self.mp_proxy.STATES_LONG,
                       'countries': self.mp_proxy.COUNTRIES_LONG}
            self.viewComponent.response.out.write(template.render(tfile, tvalues))


class MpsMediator(Mediator, IMediator):
    NAME = "MpsMediator"

    def __init__(self, view_component):
        super(MpsMediator, self).__init__(MpsMediator.NAME, view_component)
        self.mp_proxy = self.facade.retrieve_proxy(model.MpProxy.NAME)

    def listNotificationInterests(self):
        return [app_facade.AppFacade.MPS_GOT]

    def handleNotification(self, note):
        note_name = note.getName()

        if note_name == app_facade.AppFacade.MPS_GOT:
            tfile = os.path.join(os.path.dirname(__file__), 'templates/home.html')
            tvalues = {'mps': self.mp_proxy.get_all_mps()}
            self.viewComponent.response.out.write(template.render(tfile, tvalues))
